package com.learn.thread;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

/**
 *  集合类线程不安全，
 *  用synchronized同步代码块解决
 */

public class TestUnSafeThreadSynchronized3 {
    public static void main(String[] args) throws InterruptedException {
        List<String> list = new ArrayList<>();
        int threadCount = 10_000;
        CountDownLatch latch = new CountDownLatch(threadCount);
        for (int i = 0; i < threadCount; i++) {
            new Thread(() -> {
                synchronized (list) {
                    list.add(Thread.currentThread().getName());
                }
                latch.countDown(); // 线程执行完就减1
            }).start();
        }
        latch.await(); // 主线程阻塞，直到所有线程执行完
        System.out.println(list.size()); // 输出一定是 1000
    }
}
